package com.example.zkWebClient.utils;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ZooKeeperClientUtils {

	private static final Logger LOGGER = LoggerFactory.getLogger(ZooKeeperClientUtils.class);

	private static ZooKeeper zooKeeper;

	private static class ZooKeeperClientHolder {
		private static ZooKeeper zooKeeperInner;
		static {
			try {
				final CountDownLatch latch = new CountDownLatch(1);
				ZooKeeper zooKeeper = new ZooKeeper("localhost:2181", 30000, new Watcher() {
					@Override
					public void process(WatchedEvent event) {
						if (event.getState() == KeeperState.SyncConnected && event.getType() == EventType.None) {
							latch.countDown();
						}
					}
				});
				latch.await();
				zooKeeperInner = zooKeeper;
			} catch (IOException | InterruptedException e) {
				LOGGER.error("使用默认配置(localhost:2181)初始化zookeeper客户端发生异常", e);
				e.printStackTrace();
			}
		}
	}

	private ZooKeeperClientUtils() {
	}

	public static ZooKeeper getInstance() {
		if (zooKeeper == null) {
			zooKeeper = ZooKeeperClientHolder.zooKeeperInner;
		}
		return zooKeeper;
	}

	public static void setZooKeeper(ZooKeeper client) {
		try {
			client.exists("/", false);
			zooKeeper = client;
		} catch (KeeperException | InterruptedException e) {
			e.printStackTrace();
		}
	}
}
